package widget.dress.tool
{
	import flash.display.Bitmap;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import widget.dress.DressViewer;
	import widget.dress.enum.ActionEnum;
	import widget.dress.enum.DressEnum;
	import widget.dress.mode.ActionModel;
	import widget.dress.mode.DressModel;
	
	public class CartoonTimer extends Timer{
		private var _autoPlay:Boolean = false;		
		private var action:int = 0;
		private var direct:int = 0;
		private var frame:int = 0;
		
		private var lastAction : int;
		
		private var dataMode : DressModel = null;
		private var viewer : DressViewer = null;
		public function CartoonTimer(data:DressModel,view:DressViewer,delay:Number, repeatCount:int=0)
		{
			super(delay, repeatCount);
			dataMode = data;
			viewer = view;
			addEventListener(TimerEvent.TIMER, timerHandle);
		}
		
		public override function reset() : void {
			super.reset();
			autoPlay = false;
			action = 0;
			direct = 0;
			frame = 0;
			lastAction = 0;
		}
		
		public function set autoPlay(b:Boolean):void{
			this._autoPlay = b;
			if(this._autoPlay){
				this.reset();
				this.start()
			}else{
				this.stop();
			}
		}
		
		public function get autoPlay():Boolean{
			return this._autoPlay;
		}
		
		public function getAction():int{
			return this.action;
		}
		
		public function getDirect():int{
			return this.direct;
		}
		
		public function getFrame():int{
			return this.frame;
		}
		
		public function setCurrentStatus(act : int, dir : int = -1, frm : int = -1) : void {
			if(act!=1){
				this.lastAction = this.action;
				this.frame = 0;
			}
			this.action = act;
			this.direct = dir;
			this.frame = frm;	
		} 
		
		private function timerHandle(e:TimerEvent = null) : void {	
			if(dataMode.actionStatus == ActionEnum.ACTION_STAND){
				if(action != DressEnum.MOVE_BY_READY){
					action = DressEnum.MOVE_BY_STAND;
				}
			}
			
			if(viewer.getDataByAction(action) == null){
				if(viewer.getDataByAction(DressEnum.MOVE_BY_STAND)!=null)
					action = DressEnum.MOVE_BY_STAND;
				else
					return;
			}
			var actMode:ActionModel = viewer.getDataByAction(action);
			direct = direct % actMode.dataLength;
			var dirModel:ActionModel = actMode.getModel(direct);
			if(dirModel == null){
				return;
			}
			frame = frame % dirModel.dataLength;
			var bitmap:Bitmap = null;
			bitmap = dirModel.getModel(frame).bitmap;
			viewer.addDress(bitmap);
			frame++;
			if(action == DressEnum.MOVE_BY_FIGHT){
				if(frame == dirModel.dataLength){
					action = DressEnum.MOVE_BY_READY;
				}
			}
		}
		
		public function dispose() : void {
			this.stop();
			this.dataMode = null;
			this.viewer = null;
			this.removeEventListener(TimerEvent.TIMER, timerHandle);
		}
	}
}